<template>
  <TopNavBar :title="_t18('25_title')" rightType="true" @rightClick="handleRightClick" type="back" />
  <div class="quant-contract-page">
    <div class="header">
      <div class="tabs">
        <div :class="['tab', {active: activeTab === 'USD'}]" @click="activeTab = 'USD'">USD</div>
        <div :class="['tab', {active: activeTab === 'Web3'}]" @click="activeTab = 'Web3'">Web3</div>
        <div :class="['tab', {active: activeTab === 'NFT'}]" @click="activeTab = 'NFT'">NFT</div>
      </div>
      <img class="header-icon" src="@/assets/defi/hl.png" alt="hl" @click="goQuantContractShow" style="cursor:pointer;" />
    </div>

    <!-- 币种选择卡片 -->
    <div class="swap-cards" ref="swapCardsContainer">
      <div 
        v-for="(card, index) in currentSwapCards" 
        :key="index"
        :class="['swap-card', {selected: selectedCard === index}]" 
        @click="usdtClick(index, card)"
      >
        <div>
            <img class="coin-icon" src="/static/no-rename/usd.png" alt="USD" />
            <span>USD</span>
        </div>
        <span class="arrow">⇄</span>
        <div>
            <img class="coin-icon" :src="card.icon" :alt="card.name" />
            <span>{{ card.name }}</span>
        </div>
        <span class="arrow">⇄</span>
        <div>
            <img class="coin-icon" src="/static/no-rename/usd.png" alt="USD" />
            <span>USD</span>
        </div>
      </div>
    </div>

    <!-- 交易所 -->
    <div class="exchange-section">
      <div class="exchange-title">{{ _t18('25_buyExchange') }}</div>
      <div class="exchange-card buy" style="position:relative;">
        <div class="exchange-row">
          <span class="exchange-label buy-label">{{ _t18('25_buyUsd') }} <span class="amount">{{ buyyPrice }}</span></span>
        </div>
        <div class="exchange-row">
          <div>
            <img
              v-if="buyExchange?.icon"
              class="exchange-icon"
              :src="buyExchange.icon"
              :alt="buyExchange.exchangeName"
              @error="e => e.target.style.display = 'none'"
            />
            <span class="exchange-name">{{ buyExchange?.exchangeName }}</span>
          </div>
          <div class="dd-icon-box" @click="showBuyPopup = !showBuyPopup">
            <svg width="24" height="24" viewBox="0 0 24 24">
              <path d="M7 10l5 5 5-5" stroke="#555" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
        </div>
        <div v-if="showBuyPopup" class="huobi-popup">
          <div class="popup-content">
            <div 
              v-for="(exchange, index) in exchanges" 
              :key="index"
              :class="['exchange-option', { selected: buyExchange?.exchangeName === exchange.exchangeName }]"
              @click="selectBuyExchange(exchange)"
            >
              <img :src="exchange.icon" style="width:24px;height:24px;" />
              {{ exchange.exchangeName }}
            </div>
          </div>
        </div>
      </div>

      <div class="exchange-title">{{ _t18('25_sellExchange') }}</div>
      <div class="exchange-card sell" style="position:relative;">
        <div class="exchange-row">
          <span class="exchange-label sell-label">{{ _t18('25_sellUsd') }} <span class="amount">{{ sellPrice }}</span></span>
        </div>
        <div class="exchange-row">
          <div>
           <img
             v-if="sellExchange?.icon"
             class="exchange-icon"
             :src="sellExchange.icon"
             :alt="sellExchange.exchangeName"
             @error="e => e.target.style.display = 'none'"
           />
            <span class="exchange-name">{{ sellExchange?.exchangeName }}</span>
          </div>
          <div class="dd-icon-box" @click="showSellPopup = !showSellPopup">
            <svg width="24" height="24" viewBox="0 0 24 24">
              <path d="M7 10l5 5 5-5" stroke="#555" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
        </div>
        <div v-if="showSellPopup" class="huobi-popup">
          <div class="popup-content">
            <div 
              v-for="(exchange, index) in exchanges" 
              :key="index"
              :class="['exchange-option', { selected: sellExchange?.exchangeName === exchange.exchangeName }]"
              @click="selectSellExchange(exchange)"
            >
              <img :src="exchange.icon" style="width:24px;height:24px;" />
              {{ exchange.exchangeName }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 下单区 -->
    <div class="order-section">
      <div class="order-row label">{{ _t18('25_selectTime') }}</div>
      <div class="order-row time-select">
        <div class="time-dropdown" @click="showTimePopup = !showTimePopup" style="position:relative;">
          <img src="@/assets/defi/time.png" class="time-icon" alt="time" />
          <span>{{ formatPeriod(cycleObj.period) }}</span>
          <img src="@/assets/defi/into.png" class="arrow" alt="arrow" />
          <div v-if="showTimePopup" class="time-popup-overlay" @click="showTimePopup = false">
            <div class="time-popup" @click.stop>
              <div class="time-popup-header">
                <span>{{ _t18('25_timeTitle') }}</span>
                <div class="close-btn" @click="showTimePopup = false">×</div>
              </div>
              <div class="time-options">
               
				<div 
				  v-for="(item, index) in cycleList" 
				  :key="index"
				  :class="['time-option', { selected: cycleIndex === index }]"
				  @click="selectTime(index, item)"
				>
				  {{ formatPeriod(item.period) }}
				</div>

				
              </div>
            </div>
          </div>
        </div>
        <div class="rise-fall-btns">
          <button :class="['rise-btn', {active: riseFall===1}]" @click="riseFall=1">{{ _t18('25_rise') }}</button>
          <button :class="['fall-btn', {active: riseFall===0}]" @click="riseFall=0">{{ _t18('25_fall') }}</button>
        </div>
      </div>

      <div class="order-row label">{{ _t18('25_buyAmount') }}</div>
      <div class="order-row amount-row">
        <div class="usd-box">
          <img src="/static/no-rename/usd.png" class="usd-icon" alt="USD" />
          <span>USD</span>
        </div>
<input
  class="amount-input"
  :placeholder="`>= ${cycleObj?.minAmount || 0} USD`"
  v-model="amount"
  type="number"
  @input="onAmountInput"
/>


      </div>
      <div class="order-row balance">{{ _t18('25_balance') }}：{{ availableBalance }} USDT</div>
      <button class="order-btn" @click="handleOrderBtn">{{ _t18('25_createOrder') }}</button>
    </div>

    <!-- 订单进度弹窗 -->
    <div v-if="showOrderProgress" class="order-progress-modal" @click.self="closeOrderProgress">
      <div class="order-progress-content">
        <img src="/static/img/WAB_b2d79c23_u2o.b1482901.svg" class="order-progress-icon" />
        <div class="order-progress-title">{{ _t18('25_aiRunning') }}</div>
        <div class="order-progress-desc">
          <div v-if="currentTyped">{{ currentTyped }}</div>
        </div>
        <div class="order-progress-bar-wrap">
          <div class="order-progress-bar-bg">
            <div class="order-progress-bar" :style="{width: progress+'%'}"></div>
          </div>
          <div class="order-progress-percent" :style="{left: `calc(${progress}% - 30px)`}">{{ progress.toFixed(2) }}%</div>
        </div>
      </div>
    </div>

    <!-- 简单确认弹窗 -->
    <div v-if="showSimpleConfirm" class="simple-confirm-mask" @click.self="closeSimpleConfirm">
      <div class="simple-confirm-modal">
        <div class="simple-confirm-title">{{ _t18('25_confirmOrder') }}</div>
        <div class="simple-confirm-btns">
          <button class="simple-cancel" @click="closeSimpleConfirm">{{ _t18('25_cancel') }}</button>
          <button class="simple-ok" @click="handleSimpleConfirm">{{ _t18('25_confirm') }}</button>
        </div>
      </div>
    </div>

    <!-- 确认下单弹窗 -->
    <div v-if="showConfirmModal" class="confirm-modal-mask" @click.self="closeConfirmModal">
      <div class="confirm-modal">
        <div class="confirm-modal-header">
          <span>{{ _t18('25_orderInfo') }}</span>
          <span class="confirm-modal-close" @click="closeConfirmModal">×</span>
        </div>
        <div class="confirm-modal-timer">
          <span class="timer-box red">{{ String(Math.floor(countDown/3600)).padStart(2, '0') }}</span>
          <span class="timer-box green">{{ String(Math.floor((countDown % 3600) / 60)).padStart(2, '0') }}</span>
          <span class="timer-box yellow">{{ String(countDown % 60).padStart(2, '0') }}</span>
        </div>
        <div class="confirm-modal-info">
          <div class="row"><span class="label">{{ _t18('25_direction') }}</span><span v-if="riseFall==1" class="value green">{{ _t18('25_rise') }}</span><span v-if="riseFall==0" class="value red">{{ _t18('25_fall') }}</span></div>
          <div class="row"><span class="label">{{ _t18('25_amount') }}</span><span class="value">{{ amount }}U</span></div>
          <div class="row"><span class="label">{{ buyExchange?.exchangeName }} {{ _t18('25_price') }}</span><span class="value">{{ buyyPrice }}</span></div>
          <div class="row"><span class="label">{{ sellExchange?.exchangeName }} {{ _t18('25_price') }}</span><span class="value">{{ sellPrice }}</span></div>
          <div class="row"><span class="label">{{ _t18('25_profit') }}</span><span class="value">--</span></div>
        </div>
        <div class="confirm-modal-btns">
          <button class="view-btn" @click="handleViewOrder">{{ _t18('25_viewOrder') }}</button>
          <button class="continue-btn" @click="handleContinueOrder">{{ _t18('25_continueOrder') }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onUnmounted } from 'vue'
//import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { getPeriodList, createSecondContractOrder } from '@/api/trade/index'
import { useTradeStore } from '@/store/trade/index'
import { getContractListApi } from '@/api/ai/index'
import { useToast } from '@/hook/useToast'
import { _t18 } from '@/utils/public'
import { useRouter, useRoute } from 'vue-router' // ✅ 新增 useRoute



/**
 * 格式化周期显示
 * 如果 ≥ 86400 秒，则换算为天；否则显示秒
 */
/**
 * 格式化周期显示
 * 如果 ≥ 86400 秒，则换算为天；否则显示秒
 */
function formatPeriod(period) {
  const val = Number(period)
  if (!val || isNaN(val)) return '--'

  if (val >= 86400) {
    const days = Math.floor(val / 86400)
    return `${days}${_t18('day')}` // ✅ 无需区分单复数
  } else {
    return `${val}${_t18('second')}` // ✅ 秒同理
  }
}


const route = useRoute() // ✅ 新增
const { _toast, _showName } = useToast()
const tradeStore = useTradeStore()
const props = defineProps({
  quickOrder: {
    type: Boolean,
    default: false
  }, 
  aiType: {
    type: Number,
    default: 2
  }
})
console.log('QuantContract.vue quickOrder prop:', props.quickOrder)
const activeTab = ref('USD')
const riseFall = ref(1)
const selectedCard = ref(0) // 默认选中第一个卡片
const router = useRouter()
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const userStore = useUserStore()
// 用户余额信息
const { asset } = storeToRefs(userStore)

// const availableBalance = ref('') //  可用余额

// availableBalance.value =
//     asset.value.filter((item) => {
//       return item.symbol === 'usdt' && item.type === 4
//     })[0].availableAmount + ''
const availableBalance = computed(() => {
  const target = asset.value.find(
    item => item.symbol === 'usdt' && item.type === 4
  )
  return target ? String(target.availableAmount) : '0'
})

// 监听标签页切换，重置选中的卡片
watch(activeTab, () => {
  selectedCard.value = 0
})

function handleRightClick() {
  router.push('/quantContractOrder')
}
function goQuantContractShow() {
  router.push(`/quantContractShow?symbol=${currentSwapCards.value[selectedCard.value].name.toLowerCase()}`)
}
const showBuyPopup = ref(false)
const showSellPopup = ref(false)



// 不同标签页的swap-card数据
// const swapCardsData = {
//   USD: [
//     {id: 42, symbol:'btcusdt', name: 'BTC', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/2089c85a1e9a4724b650b577eca51732.png' },
//     {id: 43, symbol:'ethusdt', name: 'ETH', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/ede2393ae55247b686b96c38231d4676.png' },
//     {id: 45, symbol:'bchusdt', name: 'BCH', icon: 'https://besteth.oss-cn-hongkong.aliyuncs.com/09fcfc35fd5244a29a78f701657aca4epng' },
//     {id: 44, symbol:'xrpusdt', name: 'XRP', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/04763b91be644060b5f9fb43306753b3.png' },
//     {id: 46, symbol:'dccusdt', name: 'DCC', icon: 'https://besteth.oss-cn-hongkong.aliyuncs.com/1dcd2252dd304fb09174a0843006ce39png' },
//     {id: 47, symbol:'btcusdt', name: 'CYY', icon: 'https://besteth.oss-cn-hongkong.aliyuncs.com/4c3c87eee0704c6ab5e245dc08383f42png' }
//   ],
//   Web3: [
//     {id: 48, name: 'AXS', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/ba7e6c46188f429c96ffcd7bb7131d6b.png' },
//     {id: 49, name: 'ALICE', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/f35b6304b24544bd8b62fa5da770139b.png' },
//     {id: 50, name: 'SAND', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/1607afaf334b4733aa8b11b1c1d8ce69.png' },
//     {id: 53, name: 'ENJ', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/1607afaf334b4733aa8b11b1c1d8ce69.png' },
//     {id: 57, name: 'YGG', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/c10c9f88b78149d290115209bb3ca961.png' }
//   ],
//   NFT: [
//     {id: 58, name: 'APE', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/5b3179e7e6bd408ba9eba265ab9519f5.png' },
//     {id: 59, name: 'TMT', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/1498ca8227cd49d096304bb428816bfb.png' },
//     {id: 60, name: 'IMF', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/2ec1f2a6445544ab92593e9e8ae7b2eb.png' },
//     {id: 61, name: 'CHR', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/adc7811c613748e99e3009502d560677.png' },
//     {id: 62, name: 'OGN', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/787ea8921241480684ed92f595c53624.png' }
//   ]
// }

const swapCardsData = computed(() => {
  const result = {}

  tradeStore.secondContractCoinList.forEach(item => {
    if (item.coinType == 2) {
      // 分组字段（比如 USD / Web3 / NFT）
      const type = item.remark || 'USD'  // 默认分到 USD
      if (!result[type]) result[type] = []

      // 根据是否有 symbol 决定结构
      result[type].push({
        id: item.id,
        symbol: item.symbol,
        name: item.coinUpperCase,
        icon: item.logo
      })
    }
    
  })

  return result
})

console.log(tradeStore.secondContractCoinList)
console.log(swapCardsData.value)

// 计算当前标签页的swap-cards
const currentSwapCards = computed(() => {
  return swapCardsData.value[activeTab.value] || swapCardsData.USD
})
console.log(currentSwapCards.value)
/**
 * 币种价格详情
 */
const coinPriceInfo = computed(() => tradeStore.allCoinPriceInfo[currentSwapCards.value[selectedCard.value].name.toLowerCase()])
// console.log(tradeStore.allCoinPriceInfo)
// console.log(currentSwapCards.value[selectedCard.value])
// console.log(coinPriceInfo)

// 交易所数据
const exchanges = ref([])


  // {id: 1, name: 'Huobi', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/949bc8d1f5d1491d8f2d57e07cf553e2.png' },
  // {id: 2, name: 'Bybit', icon: 'https://static.bybit.com/logo.png' },
  // {id: 3, name: 'Gate.io', icon: 'https://www.gate.io/images/logo.png' },
  // {id: 4, name: 'Upbit', icon: 'https://static.upbit.com/logo.png' },
  // {id: 5, name: 'Binance', icon: 'https://bin.bnbstatic.com/static/images/common/logo.png' },
  // {id: 6, name: 'Coinbase', icon: 'https://www.coinbase.com/favicon.ico' },
  // {id: 7, name: 'Kraken', icon: 'https://www.kraken.com/favicon.ico' },
  // {id: 8, name: 'Kucoin', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/ebc5ce99263441e28d8d0744aebde90a.png' },



const initExchanges = async () => {
  const res = await getContractListApi()
    if (res.code === 200) {
      // total.value = res.total
      return res.data
    } else {
      finished.value = true
    }
}

// 当前选中的交易所
const buyExchange = ref() // 默认选中Huobi
const sellExchange = ref() // 默认选中Kucoin

// 选择买入交易所
function selectBuyExchange(exchange) {
  buyExchange.value = exchange
  showBuyPopup.value = false
}

// 选择卖出交易所
function selectSellExchange(exchange) {
  sellExchange.value = exchange
  showSellPopup.value = false
}

const sellPrice = computed(() => {
  const base = Number(coinPriceInfo.value?.close) || 0
  const spread = Number(sellExchange.value?.spread) || 0
  return (base * (1 + spread)).toFixed(5)
})

const buyyPrice = computed(() => {
  const base = Number(coinPriceInfo.value?.close) || 0
  const spread = Number(buyExchange.value?.spread) || 0
  return (base * (1 + spread)).toFixed(5)
})

// 时间选择相关
const showTimePopup = ref(false)
const timeOptions = ref(['60s', '3min', '5min', '180s', '15min', '30min', '1hour', '1day'])
const cycleIndex = ref('60s')

function selectTime(index, item) {
  cycleIndex.value = index
  showTimePopup.value = false
  cycleObj.value = item
}

const amount = ref('') // 购买金额输入
const showOrderProgress = ref(false) // 控制底部弹窗
const progress = ref(0) // 进度条百分比
const progressTimer = ref(null)
const toastMsg = ref('')
const showToast = ref(false)

function usdtClick(index,item) {
  selectedCard.value = index
  getCycleList(item.id)
}

// 简单确认弹窗
const showSimpleConfirm = ref(false)
function openSimpleConfirm() {
  showSimpleConfirm.value = true
}
function closeSimpleConfirm() {
  showSimpleConfirm.value = false
}
function handleSimpleConfirm() {
  
  handleOrder()
  closeSimpleConfirm()
  
}

const cycleObj = ref({})
const cycleList = ref([]) // 周期列表

/** 获取周期 */
const getCycleList = async (id) => {
  try {
    const res = await getPeriodList({ secondId: id })
    if (res.code === 200) {
      cycleList.value = res.data
      cycleObj.value = cycleList.value[0]
    }
  } catch (error) {}
}

const showConfirmModal = ref(false)

// 确定
const buyPrice = ref(0)
// 订单id用于查询倒计时订单
const orderId = ref('')
const determine = async () => {
  // if (Number(amount.value) < cycleObj.value.minAmount) {
  //   // 最少输入
  //   return showToast(`${_showName(`minimum_input`)} ${cycleObj.value.minAmount} USDT`)
  // }
  // if (Number(amount.value) > cycleObj.value.maxAmount) {
  //   // 最多输入
  //   return showToast(`${_showName(`Maximum_input`)} ${cycleObj.value.maxAmount} USDT`)
  // }
  if (Number(amount.value) > availableBalance.value) {
    // 输入量超出可用余额
    return _toast('Input_amount_exceeds')
  }
  // if (riseFall.value == 'rise') {

  // }
  let data = {
    betContent: riseFall.value,
    betAmount: amount.value,
    openPrice: coinPriceInfo.close,
    openTime: new Date().getTime(),
    symbol: currentSwapCards.value[selectedCard.value].symbol,
    coinSymbol: currentSwapCards.value[selectedCard.value].name,
    baseSymbol: 'usdt',
    periodId: cycleObj.value.id,
    aiType: props.aiType,
    buyPlat: buyExchange.value.id,
    sellPlat: sellExchange.value.id
  }
  try {
    const res = await createSecondContractOrder(data)
    console.log(res)
    if (res.code === 200) {
      orderId.value = res.data.id
      // handelClose()
      closeSimpleConfirm()
      // openConfirmModal()
      setTimeout(() => {
        showConfirmModal.value = true
        buyPrice.value = res.data.openPrice
        countDown.value = Number(cycleObj.value.period)
        overFlag.value = true
        isCloseCountdown.value = true
      }, 1000)
    } else {
      showToast(res.msg)
    }
  } catch (error) {
    console.log(error)
  }
}

const countDown = ref(0) // 初始倒计时
const overFlag = ref(false)
import { secondContractOrderselectOrderList } from '@/api/trade/index'
// import { watch } from 'fs'
const isCloseCountdown = ref(false) // 根据关闭按钮展示是否开始倒计时
// 订单数据
const orderObj = ref(null)
const timer = ref(null)
// watchEffect(() => {
//   if (isCloseCountdown.value) {
//     if (countDown.value > 0) {
//       setTimeout(() => {
//         countDown.value--
//       }, 1000)
//     } else {
//       showConfirmModal.value = false
//       userStore.getUserInfo()
//     }
//     if (countDown.value === 1) {
//       // 调用订单接口用于展示倒计时完成
//       let data = {
//         status: 1,
//         id: orderId.value
//       }
//       try {
//         setTimeout(()=>{
//           secondContractOrderselectOrderList(data).then((res) => {
//           if (res.code === 200) {
//             orderObj.value = res.data[0]
//           } else {
//             showToast(res.msg)
//           }
//         })
//         },500)
//       } catch (error) {}
//     }
//     if (overFlag.value && countDown.value <= 0) {
//       showOver.value = true
//     }
//   }
// })

watch(() => isCloseCountdown.value, (val) => {
  if (val) {
    startCountdown()
  } else {
    stopCountdown()
  }
})

function startCountdown() {
  stopCountdown() // 避免重复
  timer.value = setInterval(() => {
    if (countDown.value > 0) {
      countDown.value--
      if (countDown.value === 1) {
        // 调用订单接口
        const data = { status: 1, id: orderId.value }
        secondContractOrderselectOrderList(data).then((res) => {
          if (res.code === 200) {
            orderObj.value = res.data[0]
          } else {
            showToast(res.msg)
          }
        })
      }
    } else {
      console.log(countDown)
      stopCountdown()
      showConfirmModal.value = false
      userStore.getUserInfo()
      if (overFlag.value) {
        showOver.value = true
      }
    }
  }, 1000)
}

function stopCountdown() {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

onBeforeUnmount(() => {
  stopCountdown()
})

// 关闭倒计时
const turnOffCountdown = () => {
  showConfirmModal.value = false
  isCloseCountdown.value = false
  emit('eventBusBrother')
}
/** 倒计时完成 */
const showOver = ref(false)
const countdownClose = () => {
  showOver.value = false
  emit('eventBusBrother')
}

// 确认下单模态窗相关

const confirmCountdown = ref(58)
const confirmTimer = ref(null)
const confirmData = ref({
  direction: '漲',
  amount: '100 USD',
  huobiPrice: '119,365',
  kucoinPrice: '119,361.5',
  profit: '--'
})

function openConfirmModal() {
  showConfirmModal.value = true
  confirmCountdown.value = 58
  if (confirmTimer.value) clearInterval(confirmTimer.value)
  confirmTimer.value = setInterval(() => {
    if (confirmCountdown.value > 0) {
      confirmCountdown.value--
    } else {
      clearInterval(confirmTimer.value)
      showConfirmModal.value = false
      availableBalance.value =
        asset.value.filter((item) => {
          return item.symbol === 'usdt'
        })[0].availableAmount + ''
    }
  }, 1000)
}
function closeConfirmModal() {
  showConfirmModal.value = false
  if (timer.value) clearInterval(timer.value)
}
function handleContinueOrder() {
  closeConfirmModal()
}
function handleViewOrder() {
  router.push('/quantContractOrder')
}

// 打字机动画相关
const typingSentences = [
  '取得買入交易',
  '正在分析最佳價格...',
  '請稍候，正在為您下單',
  'AI智能風控檢查中...',
  '訂單即將完成，請耐心等待'
]
const currentTyped = ref('') // 当前正在打的句子内容
const typingSentenceIdx = ref(0)
const typingCharIdx = ref(0)
const typingTimer = ref(null)

function startTyping() {
  currentTyped.value = ''
  typingSentenceIdx.value = 0
  typingCharIdx.value = 0
  if (typingTimer.value) clearTimeout(typingTimer.value)
  typeNextChar()
}
function typeNextChar() {
  const sentence = typingSentences[typingSentenceIdx.value]
  if (typingCharIdx.value < sentence.length) {
    currentTyped.value += sentence[typingCharIdx.value]
    typingCharIdx.value++
    typingTimer.value = setTimeout(typeNextChar, 150)
  } else {
    // 当前句打完，延迟后清空并打下一句
    setTimeout(() => {
      currentTyped.value = ''
      typingSentenceIdx.value++
      typingCharIdx.value = 0
      if (typingSentenceIdx.value < typingSentences.length) {
        typingTimer.value = setTimeout(typeNextChar, 300) // 句间延迟
      }
    }, 600)
  }
}

function handleOrder() {
  const val = Number(amount.value)

  if (!val || val <= 0) {
    _toast(_t18('25_inputEmpty'))
    return
  }

  if (cycleObj.value?.minAmount && val < Number(cycleObj.value.minAmount)) {
    _toast(`${_t18('25_minAmountTip')} ${cycleObj.value.minAmount} USDT`)
    return
  }

  if (cycleObj.value?.maxAmount && val > Number(cycleObj.value.maxAmount)) {
    _toast(`${_t18('25_maxAmountTip')} ${cycleObj.value.maxAmount} USDT`)
    return
  }

  determine()
}

function closeOrderProgress() {
  showOrderProgress.value = false
  if (progressTimer.value) clearInterval(progressTimer.value)
  if (typingTimer.value) clearTimeout(typingTimer.value)
}
function onAmountInput(event) {
  const val = Number(event.target.value)

  if (val <= 0 || isNaN(val)) {
    _toast(_t18('25_inputEmpty'))
    event.target.value = amount.value = ''
    return
  }

  if (cycleObj.value?.minAmount && val < Number(cycleObj.value.minAmount)) {
    _toast(`${_t18('25_minAmountTip')} ${cycleObj.value.minAmount} USDT`)
    amount.value = cycleObj.value.minAmount.toString()
    event.target.value = amount.value
    return
  }

  if (cycleObj.value?.maxAmount && val > Number(cycleObj.value.maxAmount)) {
    _toast(`${_t18('25_maxAmountTip')} ${cycleObj.value.maxAmount} USDT`)
    amount.value = cycleObj.value.maxAmount.toString()
    event.target.value = amount.value
    return
  }

  amount.value = event.target.value.replace(/[^\d.]/g, '')
}


function handleOrderBtn() {
  const val = Number(amount.value)

  // ✅ 未输入金额
  if (!val) {
    _toast(t('25_inputEmpty'))
    return
  }

  // ✅ 金额小于最小值
  if (cycleObj.value?.minAmount && val < Number(cycleObj.value.minAmount)) {
    _toast(`${t('25_minAmountTip')} ${cycleObj.value.minAmount} USDT`)
    return
  }

  // ✅ 金额大于最大值
  if (cycleObj.value?.maxAmount && val > Number(cycleObj.value.maxAmount)) {
    _toast(`${t('25_maxAmountTip')} ${cycleObj.value.maxAmount} USDT`)
    return
  }

  console.log('handleOrderBtn quickOrder:', props.quickOrder)

  if (props.quickOrder) {
    showOrderProgress.value = true
    progress.value = 0
    startTyping()
    if (progressTimer.value) clearInterval(progressTimer.value)
    progressTimer.value = setInterval(() => {
      if (progress.value < 100) {
        progress.value += 0.55
        if (progress.value > 100) progress.value = 100
      } else {
        clearInterval(progressTimer.value)
        determine()
      }
    }, 60)
  } else {
    openSimpleConfirm()
  }
}





const onLoad = async () => {
  try {
    const data = await initExchanges()
    exchanges.value = data
    getCycleList(currentSwapCards.value[selectedCard.value].id)
    buyExchange.value = exchanges.value[0]
    sellExchange.value = exchanges.value[1]
    
  } catch (error) {
  } finally {
    // loading.value = false
  }
}

onLoad()

onMounted(async () => {
  await onLoad()
  const { id, symbol } = route.query
  if (id || symbol) {
    for (const [group, list] of Object.entries(swapCardsData.value)) {
      const index = list.findIndex(
        item =>
          String(item.id) === String(id) ||
          item.symbol?.toLowerCase() === String(symbol)?.toLowerCase()
      )
      if (index !== -1) {
        activeTab.value = group
        selectedCard.value = index
        getCycleList(list[index].id)

        // ✅ 新增：自动滚动到选中卡片
        await nextTick(() => {
          const container = document.querySelector('.swap-cards')
          const cards = container?.querySelectorAll('.swap-card')
          if (container && cards?.[selectedCard.value]) {
            const card = cards[selectedCard.value]
            const cardLeft = card.offsetLeft
            const cardWidth = card.offsetWidth
            const containerWidth = container.offsetWidth
            container.scrollTo({
              left: cardLeft - containerWidth / 2 + cardWidth / 2,
              behavior: 'smooth'
            })
          }
        })

        break
      }
    }
  }
})


onUnmounted(() => {
  if (progressTimer.value) clearInterval(progressTimer.value)
  if (typingTimer.value) clearTimeout(typingTimer.value)
  if (confirmTimer.value) clearInterval(confirmTimer.value)
})
</script>

<style scoped>
.quant-contract-page {
  padding: 20px;
  background: #fff;
  min-height: 100vh;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border: 1px solid #ccc;
  padding: 5px;
  border-radius: 50px;
}
.tabs {
  display: flex;
  gap: 16px;
}
.tab {
  padding: 8px 24px;
  border-radius: 20px;
  color: #222;
  font-weight: 600;
  cursor: pointer;
  font-size: 16px;
}
.tab.active {
  background: #000;
  color: #fff;
}
.header-icon {
  width: 32px;
  height: 32px;
}
.swap-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  overflow-x: auto;
  scroll-behavior: smooth;
  padding: 8px 0;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}
.swap-cards::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}
.swap-card {
  background: #f8f8f8;
  border-radius: 16px;
  padding: 16px 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 500;
  flex-direction: column;
  width: 100px;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-shrink: 0;
}
.swap-card.selected {
  border: 2px solid #ccc;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
}
.coin-icon {
  width: 24px;
  height: 24px;
  margin-right: 4px;
}
.arrow {
  margin: 0 4px;
  color: #bbb;
  font-size: 18px;
}
.exchange-section {
  position: relative;
  margin-top: 24px;
  
}
.exchange-title {
  font-size: 15px;
  font-weight: 700;
  margin: 18px 0 8px 0;
}
.exchange-card {
  background: #f5f7fa;
  border-radius: 12px;
  padding: 14px 18px;
  margin-bottom: 10px;
}
.exchange-row {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  justify-content: space-between;
}
.exchange-label {
  font-size: 15px;
  font-weight: 600;
}
.buy-label {
  color: #0bb07b;
}
.sell-label {
  color: #e14c4c;
}
.amount {
  font-weight: 700;
  font-size: 16px;
}
.exchange-icon {
  width: 28px;
  height: 28px;
  margin-right: 10px;
}
.exchange-name {
  font-size: 15px;
  font-weight: 500;
}
/* ====== 优化周期、方向、金额布局 ====== */
.order-section {
  margin: 32px auto 0;
  max-width: 380px;
  border-radius: 12px;
  background: #fff;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 行标题 */
.order-row.label {
  font-size: 15px;
  font-weight: 700;
  color: #222;
  margin-bottom: 6px;
}

/* 周期 + 方向行 */
.time-select {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 10px;
}

/* 时间选择按钮 */
.time-dropdown {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 12px;
  padding: 0 14px;
  height: 42px;           /* ✅ 高度调整为更接近效果图 */
  min-width: 50px;       /* ✅ 设置最小宽度 */
  font-size: 15px;
  font-weight: 600;
  color: #222;
  cursor: pointer;
  transition: all 0.2s ease;
  box-sizing: border-box;
}
.time-dropdown:hover {
  border-color: #999;
}
.time-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
.time-dropdown .arrow {
  width: 14px;
  height: 14px;
  margin-left: auto;
}

/* Up / Down 按钮样式 */
.rise-fall-btns {
  display: flex;
  gap: 8px;
}
.rise-btn,
.fall-btn {
  width: 72px;
  padding: 8px 0;
  border-radius: 10px;
  border: 1px solid #ccc;
  font-size: 15px;
  font-weight: 600;
  background: #fff;
  color: #222;
  cursor: pointer;
  transition: all 0.2s ease;
}
.rise-btn.active {
  background: #14c35b;
  color: #fff;
  border-color: #14c35b;
}
.fall-btn.active {
  background: #f10430;
  color: #fff;
  border-color: #f10430;
}

/* ====== 金额输入部分 ====== */
.amount-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.usd-box {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 12px;
  padding: 8px 16px;
  font-size: 15px;
  font-weight: 600;
  color: #222;
  gap: 6px;
  flex: 0 0 120px;
}
.usd-icon {
  width: 22px;
  height: 22px;
  background: #14c35b;
  border-radius: 50%;
  padding: 3px;
  box-sizing: border-box;
}

.amount-input {
  flex: 1;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 12px;
  padding: 8px 14px;
  font-size: 15px;
  color: #999;
  font-weight: 500;
  text-align: center;
}
.amount-input::placeholder {
  color: #ccc;
}

/* balance 样式轻微下调 */
.balance {
  font-size: 13px;
  color: #666;
  margin-top: -6px;
  margin-bottom: 10px;
}

.order-btn {
  width: 100%;
  background: #000;
  color: #fff;
  font-size: 18px;
  font-weight: 700;
  border: none;
  border-radius: 24px;
  padding: 12px 0;
  margin-top: 8px;
  cursor: pointer;
  transition: background 0.2s;
}

.order-btn:active {
  background: #222;
}
.dd-icon {
  /* 已废弃，不再使用 */
  display: none;
}
.dd-icon-box {
  width: 40px;
  height: 40px;
  background: #f7f9fa;
  border-radius: 12px;
  border: 1px solid #eef0f3;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  cursor: pointer;
  transition: box-shadow 0.2s;
}
.dd-icon-box:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
}
.dd-icon-box svg {
  display: block;
}
.huobi-popup {
  position: absolute;
  left: 0;
  top: calc(100% + 8px);
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.12);
  max-height: 220px;
  overflow-y: auto;
  padding: 18px 20px;
  width: 100%;
  z-index: 10;
}
.popup-content > div {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 14px;
  font-size: 16px;
  font-weight: 500;
}
.exchange-option {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 8px;
}
.exchange-option:hover {
  background: #f5f5f5;
  transform: translateY(-1px);
}
.exchange-option.selected {
  background: #e8f5e8;
  color: #17AC74;
  font-weight: 600;
  border: 1px solid #17AC74;
}

/* New styles for time popup */
.time-popup {
  position: relative;
  left: 0;
  bottom: 0;
  background: #fff;
  border-radius: 20px 20px 0 0;
  box-shadow: 0 -8px 24px rgba(0,0,0,0.15);
  width: 100%;
  z-index: 1000;
  border: none;
  transform: translateY(100%);
  animation: slideUp 0.3s ease-out forwards;
}
@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}
.time-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}
.time-popup-header span {
  font-size: 18px;
  font-weight: 600;
  color: #222;
}
.close-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 400;
  color: #999;
  cursor: pointer;
  border-radius: 50%;
  transition: all 0.2s ease;
}
.close-btn:hover {
  background: #f5f5f5;
  color: #666;
}
.time-options {
  padding: 16px 0;
  max-height: 60vh;
  overflow-y: auto;
}
.time-option {
  padding: 16px 24px;
  font-size: 16px;
  font-weight: 500;
  color: #222;
  cursor: pointer;
  transition: background 0.2s ease;
  border-bottom: 1px solid #f0f0f0;
  text-align: center;
}
.time-option:last-child {
  border-bottom: none;
}
.time-option:hover {
  background: #f8f9fa;
}
.time-option.selected {
  background: #f0f8ff;
  font-weight: 600;
}
.time-popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}
.toast {
  position: fixed;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0,0,0,0.8);
  color: #fff;
  padding: 12px 28px;
  border-radius: 16px;
  font-size: 16px;
  z-index: 2000;
}
.order-progress-modal {
  position: fixed;
  left: 0; right: 0; bottom: 0; top: 0;
  background: rgba(0,0,0,0.25);
  z-index: 3000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
.order-progress-content {
  background: #fff;
  border-radius: 24px 24px 0 0;
  width: 100vw;
  max-width: 100vw;
  padding: 36px 24px 32px 24px;
  box-shadow: 0 -8px 32px rgba(0,0,0,0.12);
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: slideUp 0.3s;
}
.order-progress-icon {
  width: 48px;
  height: 48px;
  margin-bottom: 18px;
}
.order-progress-title {
  font-size: 18px;
  font-weight: 700;
  margin-bottom: 12px;
  color: #222;
}
.order-progress-desc {
  font-size: 16px;
  color: #222;
  margin-bottom: 24px;
  min-height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  transition: min-height 0.2s;
}
.order-progress-bar-wrap {
  width: 90%;
  margin: 0 auto;
  position: relative;
}
.order-progress-bar-bg {
  width: 100%;
  height: 12px;
  background: #eee;
  border-radius: 8px;
  overflow: hidden;
}
.order-progress-bar {
  height: 12px;
  background: linear-gradient(90deg, #2e7cff 0%, #4bb3ff 100%);
  border-radius: 8px;
  transition: width 0.2s;
}
.order-progress-percent {
  position: absolute;
  top: 18px;
  font-size: 14px;
  color: #fff;
  background: #2e7cff;
  border-radius: 8px;
  padding: 2px 10px;
  left: 0;
  min-width: 60px;
  text-align: center;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(46,124,255,0.08);
  transition: left 0.2s;
}
.confirm-modal-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  z-index: 4000;
  display: flex;
  align-items: center;
  justify-content: center;
}
.confirm-modal {
  background: #fff;
  border-radius: 18px;
  width: 340px;
  max-width: 90vw;
  padding: 24px 20px 20px 20px;
  box-shadow: 0 4px 32px rgba(0,0,0,0.12);
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.confirm-modal-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 700;
  margin-bottom: 18px;
}
.confirm-modal-close {
  font-size: 24px;
  color: #888;
  cursor: pointer;
  font-weight: 400;
  transition: color 0.2s;
}
.confirm-modal-close:hover {
  color: #222;
}
.confirm-modal-timer {
  display: flex;
  gap: 8px;
  margin-bottom: 18px;
}
.timer-box {
  width: 44px;
  height: 44px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-family: 'Courier New', Courier, monospace;
  font-weight: 700;
  color: #fff;
}
.timer-box.red { background: #ff5a5a; }
.timer-box.green { background: #1ecb81; }
.timer-box.yellow { background: #ffc24b; color: #222; }
.confirm-modal-info {
  width: 100%;
  margin-bottom: 18px;
}
.confirm-modal-info .row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 15px;
}
.confirm-modal-info .label {
  color: #999;
  font-weight: 500;
}
.confirm-modal-info .value {
  color: #222;
  font-weight: 600;
}
.confirm-modal-info .value.green {
  color: #1ecb81;
}
.profit-bar {
  display: inline-block;
  width: 18px;
  height: 8px;
  background: repeating-linear-gradient(90deg, #eee 0 4px, #ccc 4px 8px);
  border-radius: 4px;
  margin-left: 6px;
  vertical-align: middle;
}
.confirm-modal-btns {
  width: 100%;
  display: flex;
  gap: 16px;
  margin-top: 10px;
}
.view-btn, .continue-btn {
  flex: 1;
  padding: 10px 0;
  border-radius: 24px;
  border: none;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.view-btn {
  background: #f5f5f5;
  color: #222;
}
.continue-btn {
  background: #1ecb81;
  color: #fff;
}
.continue-btn:active {
  background: #17b06b;
}
.simple-confirm-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  z-index: 4100;
  display: flex;
  align-items: center;
  justify-content: center;
}
.simple-confirm-modal {
  background: #fff;
  border-radius: 16px ;
  width: 320px;
  max-width: 90vw;
  padding: 28px 0 0 0;
  box-shadow: 0 4px 32px rgba(0,0,0,0.12);
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.simple-confirm-title {
  font-size: 18px;
  font-weight: 700;
  color: #444;
  text-align: center;
  margin-bottom: 18px;
}
.simple-confirm-btns {
  display: flex;
  width: 100%;
  border-top: 1px solid #eee;
}
.simple-cancel, .simple-ok {
  flex: 1;
  padding: 14px 0;
  border: none;
  background: none;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  color: #444;
  transition: color 0.2s;
}
.simple-cancel {
  border-right: 1px solid #eee;
}
.simple-ok {
  color: #2e7cff;
}
.simple-ok:active {
  color: #1a5bb8;
}
</style> 